package com.lihepeng.leecode.frequency.ArrayList;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;

/**
 *给出一个有序的整数数组 A 和有序的整数数组 B ，请将数组 B 合并到数组 A 中，变成一个有序的升序数组
 */
public class Solution87 {
    /**
     * 双指针 解决数组合并问题
     * @param A
     * @param m
     * @param B
     * @param n
     */
    public void merge(int A[], int m, int B[], int n) {
        int p1 = 0;
        int p2 = 0;
        int []sorted = new int[m+n];
        int cur;
        while (p1<m || p2 <n) {
            if (p1 ==m) {
                // p1 到头了
                cur = B[p2++];
            }else if (p2 ==n) {
                cur = A[p1++];
            }else if (A[p1]<B[p2]){
                cur = A[p1++];
            }else {
                cur = B[p2++];
            }
            sorted[p1+p2-1] = cur;
        }
        for (int i=0;i!=m+n;i++) {
            A[i] = sorted[i];
        }
    }
    @Test
    public void runTest() {
        int[] arr = {1,3,7,9,0,0,0,0};
        int []arr1 = {2,4,6,10};
        merge(arr,4,arr1,4);
        System.out.println(Arrays.toString(arr));
    }
}
